import { useCallback, useEffect, useState } from 'react';
import { useRequest } from 'umi';
import usePage from './usePage';
//api 相当于一个接口
const useList = (api: any) => {
  const [data, setData] = useState({
    list: [],
    total: 0,
  });
  const { run } = useRequest(api, { manual: true });
  const init = useCallback(async ({ page, pageSize }) => {
    //初始化页面
    const res = await run({
      method: 'get',
      params: { page, pageSize },
    });
    console.log(res[0], 'res');
    setData({
      //这是不固定的接口返回来的值 后期需要修改
      list: res[0],
      total: res[1],
    });
  }, []);
  useEffect(() => {
    //初始化执行 请求返回参数
    init({ page: 1, pageSize: 10 });
  }, []);

  const search = (res: any) => {
    setData({
      //这是不固定的接口返回来的值 后期需要修改
      list: res[0],
      total: res[1],
    });
  };

  const pagination = usePage({
    total: data.total,
    current: 1,
    pageSize: 10,
    showTotal: (total: number) => `共 ${total} 条`,
    onChange: (page: number, pageSize: number) => {
      console.log('useLIst_onchange', page, pageSize);
      init({ page, pageSize });
    },
  });
  return {
    list: data.list, //表格渲染的数据
    pagination: pagination, //分页数据
    init,
    search,
  };
};
export default useList;